﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using MvcEngine.Core.Repositories;

using MvcEngine.Core.Common;

namespace MvcEngine.Core.Helpers
{
    public class LogTypes
    {
        public static readonly string Warning = "Warning";
        public static readonly string Info = "Info";
        public static readonly string Error = "Error";
    }

    public class LogHelper : ILogHelper
    {
        public LogHelper()
        {
        }

        public static ILogHelper Current
        {
            get { return IoC.Resolve<ILogHelper>(); }
        }

        public virtual void WriteWarning(string message)
        {
            Write(message, null, LogTypes.Warning);
        }

        public virtual void WriteInfo(string message)
        {
            Write(message, null, LogTypes.Info);
        }

        public virtual void WriteError(string message, Exception exception)
        {
            Write(message, exception, LogTypes.Error);
        }

        public virtual void WriteError(string message)
        {
            Write(message, null, LogTypes.Error);
        }

        public virtual void WriteError(Exception exception)
        {
            Write(exception.Message, exception, LogTypes.Error);
        }

        public virtual void Write(string message, Exception exception, string type)
        {
            Log log = IoC.Resolve<Log>();
            log.Id = Guid.NewGuid();
            if (SiteContext.Current != null && SiteContext.Current.Site != null && SiteContext.Current.Site.Id != Guid.Empty)
                log.SiteId = SiteContext.Current.Site.Id;
            else
                log.SiteId = null;
            log.Message = HttpUtility.HtmlEncode(message);
            if (exception != null)
                log.Exception = HttpUtility.HtmlEncode(exception.ToString());
            log.Type = type;
            log.CreatedDate = DateTime.Now;

            try
            {
                if (HttpContext.Current != null)
                {
                    string str = string.Format("<br/><br/>------------------------------------------<br/>" +
                        "Path and query: {0};<br/>Absolute path: {1};<br/>Authority: {2};<br/>Browser: {3}",
                        HttpContext.Current.Request.Url.PathAndQuery,
                        HttpContext.Current.Request.Url.AbsolutePath,
                        HttpContext.Current.Request.Url.Authority,
                        HttpContext.Current.Request.Browser.Browser);
                    log.Message += str;
                }
            }
            catch
            {

            }
            //if (UserContext.Current.User != null)
            //    log.CreatedBy = UserContext.Current.User.Id;
            CommonManager.Current.Save(log);
        }
    }
}
